package com.xiaoq.sites.endpoint;

import java.io.IOException;
import java.net.URI;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xiaoq.apis.user.IMerchantMgrApi;
import com.xiaoq.apis.user.IVerificationCodeApi;
import com.xiaoq.apis.user.MerchantMgrInfo4Vo;
import com.xiaoq.coms.GenericResponse;
import com.xiaoq.coms.util.MapUtil;

import com.xiaoq.qiniu.QiNiuSpaceEnum;
import com.xiaoq.qiniu.UploadUtil;
import com.xiaoq.sites.entity.MerchantEntity;
import com.xiaoq.sites.entity.SitesEntity;
import com.xiaoq.sites.service.IMerchantService;
import com.xiaoq.sites.service.ISitesService;
import com.xiaoq.system.entity.ZoneMasterEntity;
import com.xiaoq.system.service.IZoneMasterService;
import com.xiaoq.web.HttpsRestTemplate;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

@RestController
@RequestMapping("/api/v1/merchant")
@Api(tags={"商家/景区工商登记信息管理接口"})
public class MerchantEndpoint {

	@Autowired
	private IMerchantService merchantSer;
	
	@Autowired
	private IZoneMasterService zoneMasterSer;
	
	@Reference(interfaceClass=IMerchantMgrApi.class,check=false, version="1.0.0")
	private IMerchantMgrApi merchantMgrDubboApi;
	
	@Reference(interfaceClass=IVerificationCodeApi.class,check=false, version="1.0.0")
	private IVerificationCodeApi verification;
	
	@Value("${yunyingAdress}")
	private String yunyingAdress;

	
	@Autowired
	private ISitesService sitesSer;
	
	@Autowired
	private HttpsRestTemplate rest;
	

	private static final Logger LOG = LoggerFactory.getLogger(MerchantEndpoint.class);


	@ApiOperation(value = "提交资质", notes = "提交资质")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "提交资质") })
	@PostMapping(value = "", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> qualification(
			@RequestParam(value = "name") @ApiParam(value = "企业名称") String name,
			@RequestParam(value = "buziLicNo") @ApiParam(value = "企业执照") MultipartFile buziLicNo,
			@RequestParam(value = "buziNo") @ApiParam(value = "工商登记号") String buziNo,
			@RequestParam(value = "corpReprz") @ApiParam(value = "法人代表名称") String corpReprz,
			@RequestParam(value = "smsCode") @ApiParam(value = "验证码") String smsCode,
			@RequestParam(value = "corpFrontPhoto") @ApiParam(value = "法人正面证件照") MultipartFile corpFrontPhoto,
			@RequestParam(value = "corpReversePhoto") @ApiParam(value = "法人反面证件照") MultipartFile corpReversePhoto,
			HttpServletRequest request) {
		String imgUrl = null;
		String userId = (String) request.getAttribute("userId");
		MerchantMgrInfo4Vo merchantMgrInfo = merchantMgrDubboApi.findMerMgr(userId);
		String mobile = merchantMgrInfo.getMobile(); // 这个就是管理员的电话了
		// 我默认到这里的时候肯定是已经有店铺的，不管以后一对多还是现在一对一
		// 肯定是先有商店后有店铺,现在一对一那我在景区创建的时候给他创建一个默认的商家
		//TODO 我先默认店铺只是景区
		
		//TODO 这里也缺一个获取验证码的接口
		
		boolean isVerified = verification.verifyVerificationCode(mobile, smsCode);
//		if (!isVerified) {
//			return GenericResponse.ng("短信验证码不正确或已超时");
//		}
		
		String sitesId = merchantMgrInfo.getShopId();
		String merchantId = merchantMgrInfo.getMerchantId();
		MerchantEntity merchant = new MerchantEntity();
		try {
			if (buziLicNo != null) {
				imgUrl = UploadUtil.easyUploadByte(buziLicNo, QiNiuSpaceEnum.XIAOQ_SITES.getName().toLowerCase(),
						QiNiuSpaceEnum.XIAOQ_SITES.getDomain());
				merchant.setBuziLicNo(imgUrl);
				LOG.info("上传七牛云的图片地址：" + imgUrl);
			}
			if (corpFrontPhoto != null) {
				imgUrl = UploadUtil.easyUploadByte(corpFrontPhoto,
						QiNiuSpaceEnum.XIAOQ_SITES.getName().toLowerCase(),
						QiNiuSpaceEnum.XIAOQ_SITES.getDomain());
				LOG.info("corpFrontPhoto上传七牛云的图片地址：" + imgUrl);
				merchant.setCorpFrontPhoto(imgUrl);
			}

			if (corpReversePhoto != null) {
				imgUrl = UploadUtil.easyUploadByte(corpReversePhoto,
						QiNiuSpaceEnum.XIAOQ_SITES.getName().toLowerCase(),
						QiNiuSpaceEnum.XIAOQ_SITES.getDomain());
				LOG.info("corpReversePhoto上传七牛云的图片地址：" + imgUrl);
				merchant.setCorpReversePhoto(imgUrl);
			}
			merchant.setId(merchantId);
			merchant.setName(name);
			merchant.setBuziNo(buziNo);
			merchant.setCorpReprz(corpReprz);
			merchant.setStatus("10");
			boolean result = merchantSer.save(merchant);
			if(result){
				boolean updateResult = sitesSer.updateAuthenStatus(sitesId, "10");
				if(updateResult){
					merchantMgrDubboApi.updateStep(userId, 3);
					try {
						submitVarify(merchantMgrInfo, merchant);
					} catch (Exception e) {
						LOG.error(e.getMessage(),e);
					}
					return GenericResponse.ok();
				}
				return GenericResponse.ng("资格认证上传失败！");
			}
			return GenericResponse.ng("资格认证上传失败！");

		} catch (IOException e) {
			LOG.error("七牛云上传异常！", e);
			return GenericResponse.ng("资格认证上传失败！");
		}
	}
	
	@Async
	public boolean submitVarify(MerchantMgrInfo4Vo merchantMgrInfo, MerchantEntity merchant) {
		Map<String, Object> body = MapUtil.buildMapKVGen(
				new Object[][] { { "account", merchantMgrInfo.getMobile() }, { "buziLicNo", merchant.getBuziLicNo() },
						{ "buziNo", merchant.getBuziNo() }, { "corpReprz", merchant.getCorpReprz() },
						{ "licence", merchant.getCorpFrontPhoto() + "|" + merchant.getCorpReversePhoto() },
						{ "name", merchant.getName() }, { "phone", merchantMgrInfo.getMobile() }, { "type", 10 },
						{ "id", merchant.getId() },

				}, String.class, Object.class);

		String respStr = post(yunyingAdress + "/admin/merchant/createMerchant", body);
		LOG.info(respStr);
		return true;

	}
	
	@ApiOperation(value = "运营后台审核资质", notes = "运营后台审核资质")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "运营后台审核资质") })
	@PutMapping(value = "/verify", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> varifyMerchant(@RequestParam(value="merchantId",required=true)@ApiParam(value="审核商店的Id",required=true)String merchantId,@RequestParam(value="status",required=true)@ApiParam(value="20审核成功30审核失败",required=true)String status) {
		MerchantEntity merchant = merchantSer.findById(merchantId);
		merchant.setStatus("20");
		merchantSer.save(merchant);
		SitesEntity sites = sitesSer.findSitesByMerchantId(merchantId);
		MerchantMgrInfo4Vo  merchantMgrInfo = merchantMgrDubboApi.findByIdByMerchantId(merchantId);
		sites.setStatus("20");
		sites.setAuthenStatus("20");
		sitesSer.addSites(sites);
		merchantMgrDubboApi.updateStep(merchantMgrInfo.getId(), 4);
		
		ZoneMasterEntity provinceZone = zoneMasterSer.getZoneMasterByCode(sites.getZoneProvince());
		ZoneMasterEntity cityZone = zoneMasterSer.getZoneMasterByCode(sites.getZoneCity());
		ZoneMasterEntity districtZone = zoneMasterSer.getZoneMasterByCode(sites.getZoneDistrict());
		
		provinceZone.setOnlineFlag("1");
		int provinceOnlineCount = provinceZone.getOnlineCount();
		provinceZone.setOnlineCount(provinceOnlineCount+1);
		zoneMasterSer.save(provinceZone);
		
		cityZone.setOnlineFlag("1");
		int cityOnlineCount = cityZone.getOnlineCount();
		cityZone.setOnlineCount(cityOnlineCount+1);
		zoneMasterSer.save(cityZone);
		
		districtZone.setOnlineFlag("1");
		int districtOnlineCount = districtZone.getOnlineCount();
		districtZone.setOnlineCount(districtOnlineCount+1);
		zoneMasterSer.save(districtZone);
		
		return GenericResponse.ok();
	}
	
	private String post(String url, Map<String, Object> body) {
		HttpEntity<Map<String, Object>> reqEntity = new HttpEntity<>(body);
		String respStr = null;
		try {
			respStr = rest.postForObject(new URI(url), reqEntity, String.class);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return respStr;
	}
}
